package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import util.DBUtil;

@WebServlet("/getMember")
public class GetMemberServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonResponse = mapper.createObjectNode();

        String memberId = request.getParameter("id");

        if (memberId == null || memberId.isEmpty()) {
            jsonResponse.put("message", "成员ID不能为空");
            out.print(mapper.writeValueAsString(jsonResponse));
            return;
        }

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String selectSQL = "SELECT * FROM users WHERE id = ?";
            preparedStatement = connection.prepareStatement(selectSQL);
            preparedStatement.setInt(1, Integer.parseInt(memberId));
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                jsonResponse.put("id", resultSet.getInt("id"));
                jsonResponse.put("name", resultSet.getString("name"));
                jsonResponse.put("groupId", resultSet.getInt("group_id"));
            } else {
                jsonResponse.put("message", "未找到成员");
            }
            out.print(mapper.writeValueAsString(jsonResponse));
        } catch (SQLException e) {
            jsonResponse.put("message", "查询成员时发生错误");
            out.print(mapper.writeValueAsString(jsonResponse));
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, resultSet);
        }
    }
}
